<!--vue模板-->
<template>
    <el-dialog
      :model-value="visible"
      :title="data.id != undefined ? '修改' : '新增'"
      width="800"
      :close-on-click-modal="false"
      @close="cls"
    >
      <el-form
        ref="formRel"
        :model="data"
        label-width="120px"
        style="max-width: 800px"
      >
        <el-form-item label="上级分类：" prop="parentId">
          <el-input placeholder="请输入" v-model="data.parentId" />
        </el-form-item>
  
        <el-form-item label="分类名称:" prop="name">
          <el-input placeholder="请输入" v-model="data.name" />
        </el-form-item>
  
        <el-form-item label="表格类型:">
          <el-select
            placeholder="下拉选择"
            style="width: 100vw"
            v-model="data.categoryCode"
          >
            <el-option
              v-for="item in categoryOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
  
        <el-form-item label="自定义字段:">
          <el-input
            type="textarea"
            :rows="5"
            placeholder="请输入"
            v-model="data.fields"
          />
        </el-form-item>
  
        <div style="text-align: right">
          <el-button type="primary" @click="save">保存</el-button>
          <el-button type="info" @click="cls">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </template>
  
  <!--vue 组件选项定义-->
  <script setup>
  import { ref } from "vue";
  import { ElMessage } from "element-plus";
  import { saveCategory, updateCategory } from "@/api/category.js";
  
  //表单引用
  const formRel = ref(null);
  //响应式对象
  const data = ref({
    id: "",
    name: "",
    parentId: "",
    categoryCode: "",
    fields: ""
  });
  //定义属性
  const props = defineProps({
    visible: {
      type: Boolean,
      default: false
    }
  });
  //声明事件
  const emits = defineEmits(["close", "refresh"]);
  //产产品分类选型
  const categoryOption = ref([
    { value: "1", label: "产品询价单" },
    { value: "2", label: "筛网询价模板" },
    { value: "3", label: "托辊询价模板" }
  ]);
  
  //方法
  function cls() {
    //通知父组件  我要关闭了
    emits("close");
  }
  
  //保存
  async function save() {
    let res;
    if (data.value.id != undefined) {
      //修改
      res = await updateCategory(data.value);
    } else {
      //新增
      res = await saveCategory(data.value);
    }
  
    if (res.code == 200) {
      ElMessage({
        message: "保存成功",
        type: "success"
      });
      //通知父组件刷新数据
      emits("refresh");
      cls();
    }
  }
  
  function init(id, name, parentId) {
    if (id != undefined) {
      //修改
      data.value.name = name;
      data.value.id = id;
    } else {
      // 新增
      data.value.name = "";
      delete data.value.id;
      delete data.value.categoryName;
    }
    data.value.parentId = parentId;
  }
  
  defineExpose({ init });
  </script>
  
  <!--vue样式 scoped当前样式只适用于当前组件-->
  <style scoped></style>
  
